<?php
declare(strict_types=1);
/**
 * Grace is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using Grace.
 *
 * @Author kiki
 */

namespace App\Common\Service;

use App\Common\Mapper\CommonMerchantMapper;
use App\System\Model\Debug;
use App\System\Service\SystemUserService;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;

/**
 * 商家管理服务类
 */
class CommonMerchantService extends AbstractService
{
    /**
     * @var CommonMerchantMapper
     */
    public $mapper;

    #[Inject]
    protected SystemUserService $userService;

    #[Inject]
    protected CommonUserService $commonUserService;

    public function __construct(CommonMerchantMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 新增数据
     * @param array $data
     * @return int
     */
    public function save(array $data): int
    {
        // 未登录状态下，也可以增加商户
        Context::set('login_before', 1);

        $userData = [
            'dept_id' => [12761854473888],
            'nickname' => $data['user_name'],
            'username' => $data['user_name'],
            'password' => $data['password'],
            'status' => 0,
            'role_ids' => '18832889750176', // 商家管理员权限
            'avatar' => $data['logo'] ?? '',
            'post_ids' => []
        ];
        Db::beginTransaction();
        try {
            // 新增商户
            $mer_id = $this->mapper->save($data);

            // 新增后台登录用户
            $userData['mer_id'] = $mer_id;
            $sys_user_id = $this->userService->save($userData);

            // 更新商户
            $this->mapper->update($mer_id, ['sys_user_id' => $sys_user_id]);

            //新增客户端用户
            $commonUser = [
                'account' => $data['user_name'],
                'pwd' => $data['password'],
                'mer_id' => $mer_id,
            ];
            $this->commonUserService->save($commonUser);

            Db::commit();
            return $mer_id;
        } catch (\Throwable $e) {
            Db::rollBack();
            throw new NormalStatusException($e->getMessage());
        }
    }

    /**
     * 更新一条数据
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function update(int $id, array $data): bool
    {
        Db::beginTransaction();
        try {
            if (isset($data['updateSingle'])) {
                unset($data['updateSingle']);
            } else {
                $userData = [
                    'nickname' => $data['user_name'] ?? '',
                    'username' => $data['user_name'] ?? '',
                    'avatar' => $data['logo'] ?? '',
                    'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                ];

                $this->userService->mapper->updateByCondition(['mer_id' => $id], $userData);
            }
            $this->mapper->update($id, $data);

            Db::commit();
            return true;
        } catch (\Throwable $e) {
            Db::rollBack();
            throw new NormalStatusException('更新商家信息出错' . $e->getFile() . $e->getLine() . $e->getMessage());
        }
    }
}